<!--
  添加课堂组件
-->
<template>
  <div>
    <el-dialog
      v-model="outerVisible"
      :title="action ? '添加课堂' : '编辑课堂'"
    >
      <el-form
        :model="form"
        label-width="120px"
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item v-if="action" label="课程/教学班" prop="taskName">
          <el-input v-model="form.taskName" disabled/>
        </el-form-item>
        <el-form-item label="授课日期" prop="teachingDate">
          <el-date-picker
            v-model="form.teachingDate"
            type="date"
            clearable
            placeholder="请选择授课日期"
          />
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.title" :placeholder="formTitle"/>
        </el-form-item>
        <el-form-item label="开始上课时间" prop="beginTime">
          <el-date-picker
            v-model="form.beginTime"
            type="datetime"
            clearable
            placeholder="请选择开始上课时间"
          />
        </el-form-item>
        <el-form-item label="结束上课时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            clearable
            placeholder="请选择结束上课时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="addClassRoom()" :disabled="showBtn">{{action ? '添加' : '编辑'}}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts' setup>
import {
  ref, reactive, defineExpose, getCurrentInstance, defineEmits,
} from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import Request from '@/api/request/request';

const { proxy } = getCurrentInstance();
const emit = defineEmits(['getLessonList']);

// 弹窗控制属性
const outerVisible = ref<boolean>();
// 课堂表单元素
let form = ref({
  taskName: '',
  teachingDate: new Date(),
  title: '',
  beginTime: '',
  endTime: '',
});
// 当前编辑的课堂Id
const lessonId = ref<number>();
// 判断操作的业务 true:添加  false:编辑
const action = ref<boolean>(true);

// eslint-disable-next-line radix
const teachingTaskId = parseInt(sessionStorage.getItem('teachingTaskId') as string); // 教学任务id
let list = []; // 用于辅助form表单的日期校验
const showBtn = ref<boolean>(true);
const ruleFormRef = ref<FormInstance>();

// 如果老师没有写标题，则设置默认的课堂标题
const getFormTitle = () => {
  const date = new Date();
  const year = date.getFullYear(); // 获取年份
  const mon = date.getMonth() + 1; // 获取月份，月份默认从0开始
  const da = date.getDate(); // 获取日
  const day = date.getDay();
  let week;

  // eslint-disable-next-line default-case
  switch (day) {
    case 1:
      week = '星期一';
      break;
    case 2:
      week = '星期二';
      break;
    case 3:
      week = '星期三';
      break;
    case 4:
      week = '星期四';
      break;
    case 5:
      week = '星期五';
      break;
    case 6:
      week = '星期六';
      break;
    case 0:
      week = '星期日';
      break;
  }
  return `${year}-${mon}-${da}${week}的课程教学`;
};
const formTitle = getFormTitle();

// 格式化时间
const formatDateTime = (date: any, mark?:string) => {
  let d = new Date(Date.parse(date));
  const year = d.getFullYear(); // 获取年份
  const mon = d.getMonth() + 1; // 获取月份，月份默认从0开始
  const day = d.getDate(); // 获取日
  const h = d.getHours() > 10 ? d.getHours() : `0${d.getHours()}`;
  const m = d.getMinutes() > 10 ? d.getMinutes() : `0${d.getMinutes()}`;
  const s = d.getSeconds() > 10 ? d.getSeconds() : `0${d.getSeconds()}`;
  if (mark === 'datetime') {
    return `${year}-${mon}-${day} ${h}:${m}:${s}`;
  }
  return `${year}-${mon}-${day}`;
};
// 自定义表单校验规则，form表单中日期组件的自定义校验规则，会被触发两次，传进两个值，一个为前面的值，一个为现在选择的值，两次传值会导致校验错误，
// 所以我在外面定义了一个list数组，将两次传入的值都传入到数组，当数组长度大于2时，也就是当前传入是我们选择的值时再进行校验
const checkDate = (rule: any, value: any, callback: any) => {
  list.push(value);
  if (list.length >= 2) {
    if (formatDateTime(new Date()) > formatDateTime(value)) {
      ElMessage.error('时间大小错误，请重新选择正确的时间');
      showBtn.value = true;
    } else {
      list = [];
      showBtn.value = false;
      callback();
    }
  }
};

// const checkDateTime = (rule: any, value: any, callback: any) => {
//   list.push(value);
//   if (list.length >= 2) {
//     if (formatDateTime(form.value.beginTime) > formatDateTime(value)) {
//       ElMessage.error('选择上课时间不能小于下课时间');
//       showBtn.value = true;
//     } else {
//       list = [];
//       showBtn.value = false;
//       callback();
//     }
//   }
// };

// 表单校验
const rules = reactive<FormRules>({
  teachingDate: [{ validator: checkDate, trigger: 'blur' }],
  beginTime: [{ validator: checkDate, trigger: 'blur' }],
  endTime: [{ validator: checkDate, trigger: 'blur' }],
});

// 重置表单数据
const resetForm = () => {
  form.value = {
    taskName: '',
    teachingDate: new Date(),
    title: '',
    beginTime: '',
    endTime: '',
  };
};

// 添加或编辑课堂
const addClassRoom = async () => {
  let data = {
    taskId: teachingTaskId,
    title: form.value.title ? form.value.title : formTitle,
    teachingDate: Date.parse(form.value.teachingDate),
    beginTime: Date.parse(form.value.beginTime),
    endTime: Date.parse(form.value.endTime),
  };
  let resData:any = {};
  if (action.value) {
    resData = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOL_SCHOOLTEACHINGTASKLESSON, data).post();
  } else {
    data.id = lessonId.value;
    resData = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOL_SCHOOLTEACHINGTASKLESSON, data).put();
  }
  if (resData.code === 200) {
    ElMessage.success(action.value ? '添加课堂成功' : '编辑课堂成功');
    outerVisible.value = false;
    emit('getLessonList');
  }
};

// 添加课堂
const addOPen = async () => {
  resetForm();
  action.value = true;
  outerVisible.value = true;
  // 获取当前教学任务信息
  const resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLTEACHINGTASK_MANAGE, null, {
    params: {
      id: teachingTaskId,
    },
  }).get();
  if (resData.code === 200) {
    form.value.taskName = `${resData.data.data[0].schoolCourse.name}/${resData.data.data[0].schoolClass.name}`;
  }
};
// 编辑课堂
const editOPen = async (id:number) => {
  showBtn.value = false;
  action.value = false;
  outerVisible.value = true;
  lessonId.value = id;
  // 获取当前编辑的课堂信息
  const resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOL_SCHOOLTEACHINGTASKLESSON, null, {
    params: {
      id,
    },
  }).get();
  if (resData.code === 200) {
    form.value = {
      taskName: '',
      teachingDate: resData.data.data[0].teachingDate,
      title: resData.data.data[0].title,
      beginTime: resData.data.data[0].beginTime,
      endTime: resData.data.data[0].endTime,
    };
  }
};

defineExpose({
  addOPen,
  editOPen,
});
</script>

<style lang="scss" scoped>

</style>
